<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户手机号" prop="userPhone">
        <el-input v-model="queryParams.userPhone" placeholder="请输入用户手机号或姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="次卡名称" prop="cardName">
        <el-input v-model="queryParams.cardName" placeholder="请输入次卡名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="购买时间" prop="buyTimeRange">
        <el-date-picker
          v-model="buyTimeRange"
          style="width: 240px"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="handleDateRangeChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="Plus"
          size="small"
          @click="handleAddNumberCardOrder"
          v-hasPermi="['finance:numbercard:add']"
        >新增次卡订单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="Plus"
          size="small"
          @click="handleAddNumberCardRecord"
          v-hasPermi="['finance:numbercard:add']"
        >新增次卡记录</el-button>
      </el-col>


      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="numberCardOrderList"
      @sort-change="handleSortChange"
      style="width: 100%"
      stripe
    >

      <el-table-column label="序号" type="index" width="80" align="center">
        <template #default="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="userPhone" label="客户" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="cardName" label="次卡名称" align="center" min-width="150">
        <template #default="scope">
          <div style="white-space: normal; word-break: break-all; line-height: 1.4; padding: 2px 0;">{{ scope.row.cardName }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="orderCode" label="订单编号" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="buyTime" label="购买时间" align="center" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.buyTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="beginTime" label="生效时间" align="center" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.beginTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="过期时间" align="center" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="totalTimes" label="总次数" align="center" sortable="custom" />
      <el-table-column prop="useTimes" label="使用次数" align="center" sortable="custom" />
      <el-table-column prop="lastTimes" label="剩余次数" align="center" sortable="custom" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="编辑" placement="top">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleEdit(scope.row)"
              v-hasPermi="['finance:numbercard:edit']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              link
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['finance:numbercard:remove']"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="open"
      :title="title"
      width="700px"
      append-to-body
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="绑定手机号" prop="userPhone">
          <div style="display: flex; gap: 10px;">
            <el-input v-model="form.userPhone" placeholder="请输入绑定手机号" maxlength="11" show-word-limit />
            <el-button type="primary" @click="queryUser">查询用户</el-button>
          </div>
        </el-form-item>
        <el-form-item label="购买用户" prop="userName">
          <el-input v-model="form.userName" disabled placeholder="--" />
        </el-form-item>
        <el-form-item label="订单编号" prop="orderCode">
          <el-input v-model="form.orderCode" placeholder="订单编号" />
        </el-form-item>
        <el-form-item label="选择次卡" prop="cardId">
          <el-select v-model="form.cardId" placeholder="请选择次卡" @change="handleCardChange">
            <el-option v-for="card in cardOptions" :key="card.id" :label="card.name" :value="card.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间" prop="buyTime">
          <el-date-picker
            v-model="form.buyTime"
            type="datetime"
            placeholder="请选择下单时间"
            style="width: 100%"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="总金额" prop="totalAmount">
          <el-input v-model.number="form.totalAmount" placeholder="请输入总金额" type="number" />
        </el-form-item>
        <el-form-item label="支付方式">
          <div style="display: flex; flex-direction: column; gap: 10px;">
            <div style="display: flex; align-items: center; gap: 10px;">
              <span>卡结算: 账户余额(0.00):</span>
              <el-input-number v-model="form.cardPayment" :min="0" style="width: 150px;" />
            </div>
            <div style="display: flex; align-items: center; gap: 10px;">
              <span>产品账户(0.00):</span>
              <el-input-number v-model="form.productAccountPayment" :min="0" style="width: 150px;" />
            </div>
            <div style="display: flex; align-items: center; gap: 10px;">
              <span>现金支付:</span>
              <el-input-number v-model="form.cashPayment" :min="0" style="width: 150px;" />
            </div>
            <div style="display: flex; align-items: center; gap: 10px;">
              <span>银行卡支付:</span>
              <el-input-number v-model="form.bankCardPayment" :min="0" style="width: 150px;" />
            </div>
            <div style="display: flex; align-items: center; gap: 10px;">
              <span>挂账支付:</span>
              <el-input-number v-model="form.creditPayment" :min="0" style="width: 150px;" />
            </div>
            <div style="display: flex; align-items: center; gap: 10px;">
              <span>免费支付:</span>
              <el-input-number v-model="form.freePayment" :min="0" style="width: 150px;" />
            </div>
            <div style="display: flex; align-items: center; gap: 10px;">
              <span>微信支付:</span>
              <el-input-number v-model="form.wechatPayment" :min="0" style="width: 150px;" />
            </div>
            <div style="display: flex; align-items: center; gap: 10px;">
              <span>支付宝支付:</span>
              <el-input-number v-model="form.alipayPayment" :min="0" style="width: 150px;" />
            </div>
            <div style="display: flex; align-items: center; gap: 10px;">
              <span>大众点评抵扣金额:</span>
              <el-input-number v-model="form.dianpingDeduction" :min="0" style="width: 150px;" />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-radio-group v-model="form.orderStatus">
            <el-radio label="0">未付款</el-radio>
            <el-radio label="1">已完成</el-radio>
            <el-radio label="2">挂账订单</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="附件" prop="attachment">
          <el-upload
            action=""
            :auto-upload="false"
            :on-change="handleFileChange"
            :show-file-list="true"
          >
            <el-button type="primary">选取文件</el-button>
          </el-upload>
          <div class="text-tips">请上传大小不超过50MB格式为的文件</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加购买次卡记录弹框 -->
    <el-dialog
      v-model="recordOpen"
      :title="recordTitle"
      width="600px"
      append-to-body
    >
      <el-form ref="recordFormRef" :model="recordForm" :rules="recordRules" label-width="80px">
        <el-form-item label="绑定用户手机号" prop="userPhone">
          <template v-if="recordForm.id">
            <!-- 编辑模式：显示用户手机号且不可更改 -->
            <el-input
              v-model="recordForm.userPhone"
              disabled
              placeholder="--"
            />
          </template>
          <template v-else>
            <!-- 新增模式：可输入用户手机号 -->
            <div>
              <div style="display: flex; gap: 10px; margin-bottom: 5px;">
                <el-input v-model="recordForm.userPhone" placeholder="请输入用户手机号" maxlength="11" show-word-limit oninput="value=value.replace(/[^0-9]/g,'')" style="flex: 1;" />
                <el-button type="primary" @click="queryUserByPhone" :disabled="!recordForm.userPhone || recordForm.userPhone.length !== 11">查询用户</el-button>
              </div>
              <!-- 显示查询到的用户名称 -->
              <div v-if="recordForm.userName" class="text-success" style="font-size: 14px;">
                <i class="el-icon-success" /> 已查询到用户：{{ recordForm.userName }}
              </div>
            </div>
          </template>
        </el-form-item>
        <el-form-item label="次卡" prop="cardId">
          <template v-if="recordForm.id">
            <!-- 编辑模式：显示次卡名称且不可更改 -->
            <el-input
              v-model="recordForm.cardName"
              disabled
              placeholder="--"
              style="white-space: normal; word-break: break-all;"
            />
            <input type="hidden" v-model="recordForm.cardId">
          </template>
          <template v-else>
            <!-- 新增模式：可选择次卡 -->
            <el-select v-model="recordForm.cardId" placeholder="请选择次卡" popper-append-to-body @change="handleRecordCardChange">
              <el-option
                v-for="card in cardList"
                :key="card.value"
                :label="card.label"
                :value="card.value"
                style="white-space: normal; word-break: break-all; line-height: 1.4; padding: 6px 10px;"
              />
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="购买时间" prop="buyTime">
          <el-date-picker
            v-model="recordForm.buyTime"
            type="datetime"
            placeholder="请选择购买时间"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="生效时间" prop="beginTime">
          <el-date-picker
            v-model="recordForm.beginTime"
            type="datetime"
            placeholder="请选择生效时间"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="截至时间" prop="endTime">
          <el-date-picker
            v-model="recordForm.endTime"
            type="date"
            placeholder="请选择截至时间"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="总次数" prop="totalTimes">
          <el-input v-model.number="recordForm.totalTimes" placeholder="请输入总次数" type="number" />
        </el-form-item>
        <el-form-item label="使用次数" prop="useTimes">
          <el-input v-model.number="recordForm.useTimes" placeholder="请输入使用次数" type="number" />
        </el-form-item>
        <el-form-item label="剩余次数" prop="lastTimes">
          <el-input v-model.number="recordForm.lastTimes" placeholder="请输入剩余次数" type="number" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelRecord">取消</el-button>
          <el-button type="primary" :loading="recordLoading" @click="submitRecordForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import { useAppStore } from '@/store/modules/app'
import Pagination from '@/components/Pagination/index.vue'
import RightToolbar from '@/components/RightToolbar/index.vue'
import { parseTime } from '@/utils/ruoyi'
import { useRouter } from 'vue-router'
import { getCurrentInstance } from 'vue'
import axios from 'axios'

// 导入API
import { listNumberCardOrder, addNumberCardOrder, delNumberCardOrder } from '@/api/finance/numbercard'
import { addNumberCar } from '@/api/business/itemorder'
import { getAllCardList } from '@/api/goods/baseNumberCard'
import { listUser } from '@/api/system/user'

// 状态管理
const { proxy } = getCurrentInstance()
const userStore = useUserStore()
const appStore = useAppStore()
const router = useRouter()

// 表格数据
const loading = ref(false)
const total = ref(0)
const numberCardOrderList = ref([])
const open = ref(false)
const title = ref('')
const queryFormRef = ref(null)
const formRef = ref(null)

// 次卡记录相关状态
const recordOpen = ref(false)
const recordTitle = ref('添加购买次卡记录')
const recordFormRef = ref(null)
const recordLoading = ref(false)
const cardList = ref([]) // 次卡列表

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userPhone: '',
  cardName: '',
  beginTime: '',
  endTime: '',
  orderByColumn: '',
  isAsc: ''
})

// 表单数据
const form = reactive({
  id: null,
  userId: null,
  userPhone: '',
  cardName: '',
  cardId: null,
  buyTime: '',
  beginTime: '',
  endTime: '',
  totalTimes: 0,
  useTimes: 0,
  lastTimes: 0,
  itemName: null,
  orderCode: null
})

// 次卡记录表单数据
const recordForm = reactive({
  id: null,
  userId: null,
  userName: '',
  userPhone: '',
  cardId: null,
  cardName: '',
  buyTime: new Date().toISOString(),
  beginTime: new Date().toISOString(),
  endTime: '',
  totalTimes: 0,
  useTimes: 0,
  lastTimes: 0,
  days: 365
})

// 监听用户手机号变化，清空userId和userName
watch(() => recordForm.userPhone, (newVal, oldVal) => {
  if (newVal !== oldVal && recordForm.userId) {
    recordForm.userId = null
    recordForm.userName = ''
  }
})

// 次卡记录表单验证规则
const recordRules = reactive({
  userPhone: [
    { required: true, message: '请输入用户手机号', trigger: 'blur' },
    { pattern: /^1\d{10}$/, message: '请输入正确的11位手机号', trigger: 'blur' }
  ],
  cardId: [
    { required: true, message: '请选择次卡', trigger: 'change' }
  ],
  beginTime: [
    { required: true, message: '请选择生效时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择截至时间', trigger: 'change' }
  ],
  totalTimes: [
    { required: true, message: '请输入总次数', trigger: 'blur' },
    { type: 'number', min: 1, message: '总次数必须大于0', trigger: 'blur' }
  ]
})

// 表单验证
const rules = reactive({
  userId: [
    { required: true, message: '请选择用户', trigger: 'blur' }
  ],
  userPhone: [
    { required: true, message: '请输入绑定手机号', trigger: 'blur' },
    { pattern: /^1\d{10}$/, message: '请输入正确的11位手机号', trigger: 'blur' }
  ],
  cardName: [
    { required: true, message: '请输入次卡名称', trigger: 'blur' }
  ],
  buyTime: [
    { required: true, message: '请选择购买时间', trigger: 'change' }
  ],
  beginTime: [
    { required: true, message: '请选择生效时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择过期时间', trigger: 'change' }
  ],
  totalTimes: [
    { required: true, message: '请输入总次数', trigger: 'blur' },
    { type: 'number', min: 1, message: '总次数必须大于0', trigger: 'blur' }
  ]
})

// 日期范围
const buyTimeRange = ref([])

// 控制显示搜索条件
const showSearch = ref(true)

// 获取次卡订单列表
function getList() {
  loading.value = true
  // 处理日期范围
  if (buyTimeRange.value && buyTimeRange.value.length > 0) {
    queryParams.beginTime = buyTimeRange.value[0]
    queryParams.endTime = buyTimeRange.value[1]
  } else {
    queryParams.beginTime = ''
    queryParams.endTime = ''
  }

  listNumberCardOrder(queryParams).then(response => {
    numberCardOrderList.value = response.rows || []
    total.value = response.total || 0
    loading.value = false
  }).catch(error => {
    console.error('获取次卡订单列表失败:', error)
    loading.value = false
    ElMessage.error('获取数据失败，请稍后重试')
  })
}

// 监听日期范围变化
function handleDateRangeChange() {
  queryParams.pageNum = 1
  getList()
}

// 搜索按钮
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮
function resetQuery() {
  queryFormRef.value?.resetFields()
  buyTimeRange.value = []
  queryParams.pageNum = 1
  queryParams.orderByColumn = ''
  queryParams.isAsc = ''
  handleQuery()
}



// 排序触发事件
function handleSortChange(column) {
  queryParams.orderByColumn = column.prop
  queryParams.isAsc = column.order === 'ascending' ? 'asc' : 'desc'
  getList()
}

// 新增次卡订单按钮
function handleAddNumberCardOrder() {
  resetForm()
  open.value = true
  title.value = '新增次卡订单'
}

// 新增次卡记录按钮
function handleAddNumberCardRecord() {
  resetRecordForm()
  getCardList() // 打开弹框时加载次卡列表
  recordOpen.value = true
  recordTitle.value = '添加购买次卡记录'
}

// 获取次卡列表
function getCardList() {
  try {
    getAllCardList().then(res => {
      if (res && res.data) {
        cardList.value = res.data.map(item => ({
          label: item.name,
          value: item.id
        }))
      }
    })
  } catch (error) {
    ElMessage.error('获取次卡列表失败')
    console.error('获取次卡列表失败:', error)
  }
}

// 重置次卡记录表单
function resetRecordForm() {
  recordFormRef.value?.resetFields()
  Object.assign(recordForm, {
    id: null,
    userId: null,
    userName: '',
    userPhone: '',
    cardId: null,
    cardName: '',
    buyTime: new Date().toISOString(),
    beginTime: new Date().toISOString(),
    endTime: '',
    totalTimes: 0,
    useTimes: 0,
    lastTimes: 0,
    days: 365
  })
}

// 处理次卡记录表单的次卡选择变化
function handleRecordCardChange(val) {
  const selectedCard = cardList.value.find(card => card.value === val)
  if (selectedCard) {
    recordForm.cardName = selectedCard.label
    // 根据次卡类型设置默认的总次数和时间
    if (val === 1) { // 年卡
      recordForm.totalTimes = 100
      recordForm.beginTime = recordForm.buyTime
      const endDate = new Date(recordForm.buyTime)
      endDate.setFullYear(endDate.getFullYear() + 1)
      recordForm.endTime = endDate.toISOString()
    } else if (val === 2) { // 季卡
      recordForm.totalTimes = 30
      recordForm.beginTime = recordForm.buyTime
      const endDate = new Date(recordForm.buyTime)
      endDate.setMonth(endDate.getMonth() + 3)
      recordForm.endTime = endDate.toISOString()
    }
    // 确保剩余次数计算正确
    recordForm.lastTimes = recordForm.totalTimes - recordForm.useTimes
  }
}

// 删除按钮功能
function handleDelete(row) {
  ElMessageBox.confirm(
    '确定要删除这条次卡记录吗？',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 调用删除接口
    delNumberCardOrder(row.id).then(() => {
      ElMessage.success('删除成功')
      // 刷新列表
      getList()
    }).catch(error => {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    })
  }).catch(() => {
    // 用户取消删除
    ElMessage.info('已取消删除')
  })
}

// 查询用户信息函数
function queryUserByPhone() {
  const phone = recordForm.userPhone
  if (!phone || phone.length !== 11) {
    ElMessage.warning('请输入正确的手机号码')
    return
  }
  
  // 使用手机号查询用户
  listUser({ phonenumber: phone }).then(response => {
    const users = response.rows || []
    if (users.length > 0) {
      // 找到用户，这里可以根据需要设置更多字段
      ElMessage.success('查询到用户信息')
      // 将用户ID和用户名保存到recordForm中
      recordForm.userId = users[0].userId
      recordForm.userName = users[0].userName
    } else {
      ElMessage.warning('未查询到该手机号对应的用户')
    }
  }).catch(error => {
    console.error('查询用户失败:', error)
    ElMessage.error('查询用户失败，请稍后重试')
  })
}

// 编辑按钮 - 修改为使用添加购买次卡记录弹框的样式
function handleEdit(row) {
  resetRecordForm()
  recordOpen.value = true
  recordTitle.value = '编辑购买次卡记录'
  
  // 直接使用传入的row参数中的数据，特别是次卡名称
  Object.assign(recordForm, row)
  
  // 格式化时间数据
  if (recordForm.buyTime) {
    recordForm.buyTime = typeof recordForm.buyTime === 'string' ? recordForm.buyTime : recordForm.buyTime.toISOString()
  }
  if (recordForm.beginTime) {
    recordForm.beginTime = typeof recordForm.beginTime === 'string' ? recordForm.beginTime : recordForm.beginTime.toISOString()
  }
  if (recordForm.endTime) {
    recordForm.endTime = typeof recordForm.endTime === 'string' ? recordForm.endTime : recordForm.endTime.toISOString()
  }
  
  // 确保次卡名称从列表中直接使用，不修改
  recordForm.cardName = row.cardName || recordForm.cardName
}





// 次卡选项列表
const cardOptions = ref([])

// 重置表单
function resetForm() {
  formRef.value?.resetFields()
  Object.assign(form, {
    id: null,
    userId: null,
    userPhone: '',
    userName: '',
    cardId: null,
    cardName: '',
    orderCode: '',
    buyTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
    totalAmount: 0,
    cardPayment: 0,
    productAccountPayment: 0,
    cashPayment: 0,
    bankCardPayment: 0,
    creditPayment: 0,
    freePayment: 0,
    wechatPayment: 0,
    alipayPayment: 0,
    dianpingDeduction: 0,
    orderStatus: '0',
    remark: '',
    attachment: null,
    beginTime: '',
    endTime: '',
    totalTimes: 0,
    useTimes: 0,
    lastTimes: 0
  })
  
  // 加载次卡选项
  loadCardOptions()
}

// 加载次卡选项
function loadCardOptions() {
  loading.value = true
  getAllCardList().then(response => {
    const data = response.data || response
    // 确保数据格式正确，将id和name字段映射到选项中
    cardOptions.value = Array.isArray(data) ? data.map(item => ({
      id: item.id || item.cardId,
      name: item.name || item.cardName
    })) : []
  }).catch(error => {
    console.error('获取次卡列表失败:', error)
    ElMessage.error('获取次卡列表失败，请稍后重试')
    cardOptions.value = []
  }).finally(() => {
    loading.value = false
  })
}

// 查询用户
function queryUser() {
  if (!form.userPhone) {
    ElMessage.warning('请输入手机号')
    return
  }
  
  // 这里应该调用API查询用户，暂时模拟
  ElMessage.success('查询成功')
  form.userName = '测试用户'
  form.userId = 1
}

// 处理次卡选择变化
function handleCardChange(val) {
  const selectedCard = cardOptions.value.find(card => card.id === val)
  if (selectedCard) {
    form.cardName = selectedCard.name
    // 根据次卡类型设置默认的总次数和时间
    if (val === 1) { // 年卡
      form.totalTimes = 100
      form.beginTime = form.buyTime
      const endDate = new Date(form.buyTime)
      endDate.setFullYear(endDate.getFullYear() + 1)
      form.endTime = endDate.toISOString().slice(0, 10)
    } else if (val === 2) { // 季卡
      form.totalTimes = 30
      form.beginTime = form.buyTime
      const endDate = new Date(form.buyTime)
      endDate.setMonth(endDate.getMonth() + 3)
      form.endTime = endDate.toISOString().slice(0, 10)
    } else if (val === 3) { // 月卡
      form.totalTimes = 12
      form.beginTime = form.buyTime
      const endDate = new Date(form.buyTime)
      endDate.setMonth(endDate.getMonth() + 1)
      form.endTime = endDate.toISOString().slice(0, 10)
    } else if (val === 4) { // 单次体验卡
      form.totalTimes = 1
      form.beginTime = form.buyTime
      form.endTime = form.buyTime.split(' ')[0]
    }
  }
}

// 处理文件上传
function handleFileChange(file) {
  form.attachment = file.raw
  ElMessage.success('文件选择成功')
}

// 取消按钮
function cancel() {
  open.value = false
  resetForm()
}

// 取消次卡记录
function cancelRecord() {
  recordOpen.value = false
  resetRecordForm()
}

// 提交次卡记录表单
async function submitRecordForm() {
  await recordFormRef.value?.validate(async (valid) => {
    if (!valid) return
    recordLoading.value = true
    
    try {
      // 计算剩余次数
      recordForm.lastTimes = recordForm.totalTimes - recordForm.useTimes
      
      // 准备提交数据
      const submitData = {
        ...recordForm,
        userPhone: recordForm.userPhone,
        // 确保时间格式正确
        buyTime: recordForm.buyTime ? new Date(recordForm.buyTime).toISOString() : null,
        beginTime: recordForm.beginTime ? new Date(recordForm.beginTime).toISOString() : null,
        endTime: recordForm.endTime
      }
      
      // 调用接口提交数据
      let res;
      if (recordForm.id) {
        // 编辑模式 - 使用PUT请求
        res = await axios.put('/api/finance/numbercard', submitData)
      } else {
        // 新增模式 - 使用原有函数
        res = await addNumberCardOrder(submitData)
      }
      
      if (res && res.code === 200) {
        ElMessage.success('添加成功')
        recordOpen.value = false
        getList() // 重新加载列表数据
      } else {
        ElMessage.error(res.message || '添加失败')
      }
    } catch (error) {
      ElMessage.error('添加失败，请稍后重试')
      console.error('添加次卡记录失败:', error)
    } finally {
      recordLoading.value = false
    }
  })
}

// 提交表单
function submitForm() {
  formRef.value?.validate(valid => {
    if (!valid) return
    loading.value = true
    // 计算剩余次数
    form.lastTimes = form.totalTimes - form.useTimes
    
    // 根据用户要求，使用finance/numbercard接口
    // 新增使用POST方法，修改使用PUT方法
    const formData = new FormData()
    
    // 将表单数据添加到FormData中
    for (const key in form) {
      if (form.hasOwnProperty(key)) {
        formData.append(key, form[key])
      }
    }
    
    // 创建请求配置
    const config = {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }
    
    let request
    if (form.id) {
      // 修改操作 - 使用PUT方法
      request = axios.put('/api/finance/numbercard', formData, config)
    } else {
      // 新增操作 - 使用导入的API函数
      request = addNumberCar(formData)
    }
    
    request.then(() => {
      ElMessage.success('操作成功')
      open.value = false
      getList()
    }).catch(error => {
      console.error('操作次卡订单失败:', error)
      ElMessage.error('操作失败，请稍后重试')
    }).finally(() => {
      loading.value = false
    })
  })
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.small-padding {
  padding: 4px 0;
}

.fixed-width {
  width: 150px;
}
</style>